<!DOCTYPE html>
<html lang="en">
<head>
    <title>漫画列表</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
    <meta name="Keywords" content=""/>
    <meta name="description" content=""/>
    <link type="image/x-icon" href="" rel="shortcut icon">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/cropper.css">
    <link rel="stylesheet" href="css/book_list.css">
    <style>
        .test {color: #b8242c
        }
    </style>
</head>
<body>
<!--nav-->
<div class="nav container">
    <a class="nav-tag" href="" title="首页">首页</a>>
    <a class="nav-tag" href="" title="系统书单管理">系统书单管理</a>
</div>
<!--操作主页-->
<div id="handle" class="container handle">
    <div id="publicfields"></div>
    <div class="row handle-head">
        <div class="col-sm-1 handle-block">漫画ID</div>
        <div class="col-sm-1 handle-block">漫画名</div>
        <div class="col-sm-2 handle-block">漫画看点</div>
        <div class="col-sm-1 handle-block">排序值</div>
        <div class="col-sm-2 handle-block">封面图</div>
        <div class="col-sm-3 handle-block">URL</div>
        <div class="col-sm-2 handle-block">操作</div>
    </div>
    <!--单行书单-->
    <div class="row handle-body e-body">
        <form action="">
            <div class="col-md-1 handle-block">
                1
            </div>
            <div class="col-md-1 handle-block">
                漫画名
            </div>
            <div class="col-md-2 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w150 margin-auto">
                    <input type="text" class="form-control" placeholder="" value="看点文字">
                </div>
            </div>
            <div class="col-md-1 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w55 margin-auto">
                    <input type="number" class="form-control" placeholder="" value="1">
                </div>
            </div>
            <div class="col-md-2 handle-block">
                <div class="face e-face">
                    <div class="face-left">
                        <img class="e-pic" src="img/blank.jpg" alt="">
                    </div>
                    <div class="face-right">
                        <span class="glyphicon glyphicon-plus-sign face-icon face-icon-top e-add" data-config='[{"clipname":"裁剪比例1：3","clipsize":[300,900],"osspath":"test2.jpg","previewHost":"","suffix":"-middle.zymk"},{"clipname":"裁剪比例1：1","clipsize":[400,400],"osspath":"test3.jpg","previewHost":"","suffix":"-middle.zymk"},{"clipname":"裁剪比例4：3","clipsize":[800,600],"osspath":"test4","previewHost":"","suffix":"-middle.zymk"}]'></span>
                        <span class="glyphicon glyphicon-minus-sign face-icon face-icon-bottom e-clear"></span>
                    </div>
                    <input type="hidden" name="img_clip" class="e-host">
                </div>
            </div>
            <div class="col-md-3 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w150 margin-auto">
                    <input type="number" class="form-control" placeholder="" value="1">
                </div>
            </div>
            <div class="col-md-2 handle-block">
                <span class="handle-delete e-delete">删除</span>
            </div>
        </form>
    </div>
</div>
<div class="footer-place"></div>
<div class="footer">
    <div class="container">
        <button class="btn btn-default btn-sm pull-right" type="button">批量保存</button>
        <button id="addBookBtn" class="btn btn-default btn-sm pull-right" type="button">添加书单</button>
        共<span class="e-count">4</span>个系统书单
    </div>
</div>
<!--以下为弹窗/浮层-->
<!--a:裁剪modal-->

<div class="modal fade" id="clipModal" role="dialog" aria-labelledby="modalLabel" tabindex="-1">
    <div class="modal-dialog modal-lg" role="document" id="actions">
        <div class="modal-content docs-buttons">
            <div class="modal-header">
                <h5 class="modal-title" id="modalLabel">封面图设置</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="clip-wrap">
                    <div class="clip-main">
                        <div class="clip-canvas">
                            <div class="img-container">
                                <img src="img/transparent.png" alt="Picture">
                            </div>
                        </div>
                        <div class="clip-btns">
                            只支持jpg、png大小不超过2M
                            <div class="pull-right">
                                <button id="exitBtn" type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                <button id="clipBtn" type="button" class="btn btn-primary" data-method="getCroppedCanvas"><span class="docs-tooltip" data-toggle="tooltip" title="" data-original-title="cropper.getCroppedCanvas()">确定裁剪</span></button>
                            </div>
                        </div>
                    </div>
                    <div class="clip-handle">
                        <div class="clip-split">
                            <div class="cropper-aspect-box mt10 docs-toggles">
                                <div class="cropper-aspect">
                                    <div id="clipTypeBtns" class="btn-group-vertical docs-aspect-ratios" data-toggle="buttons">
                                        <!--<label class="btn btn-lg btn-primary active">-->
                                            <!--<input type="radio" class="sr-only" id="aspectRatio1" name="aspectRatio" value="2">-->
                                            <!--<span class="docs-tooltip" data-toggle="tooltip" title="aspectRatio: 16 / 8"> 16:8 </span>-->
                                        <!--</label>-->
                                    </div>
                                </div>
                            </div>
                            <div class="clip-handle-bottom">
                                <label class="btn btn-primary" for="inputImage" title="Upload image file">
                                    <input type="file" class="sr-only" id="inputImage" name="file" accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff">
                                    <span title="" data-original-title="Import image with Blob URLs">选择图片</span>
                                </label>
                                <label class="btn btn-primary clip-sub" title="submit picture">
                                    <span title="上传图片" data-original-title="submit checked picture">上传图片</span>
                                </label>
                            </div>
                        </div>
                        <div class="clip-view">
                            <!--<div class="clip-view-row toggle-wrap">-->
                                <!--<div class="clip-view-box">-->
                                    <!--<img class="toggle-view" src="img/blank.jpg" alt="">-->
                                <!--</div>-->
                                <!--<div class="clip-view-des toggle-size">-->
                                    <!--16:8-->
                                <!--</div>-->
                            <!--</div>-->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script id="bookTpl" type="text/html">
    <div class="row handle-body e-body">
        <form action="">
            <div class="col-md-1 handle-block">
                1
            </div>
            <div class="col-md-1 handle-block">
                漫画名
            </div>
            <div class="col-md-2 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w150 margin-auto">
                    <input type="text" class="form-control" placeholder="" value="看点文字">
                </div>
            </div>
            <div class="col-md-1 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w55 margin-auto">
                    <input type="number" class="form-control" placeholder="" value="1">
                </div>
            </div>
            <div class="col-md-2 handle-block">
                <div class="face e-face">
                    <div class="face-left">
                        <img class="e-pic" src="img/blank.jpg" alt="">
                    </div>
                    <div class="face-right">
                        <span class="glyphicon glyphicon-plus-sign face-icon face-icon-top e-add"  data-config='[{"clipname":"裁剪比例1：4","clipsize":[200,800],"osspath":"test1.jpg","previewHost":"","suffix":"-middle.zymk"},{"clipname":"裁剪比例1：3","clipsize":[300,900],"osspath":"test2.jpg","previewHost":"","suffix":"-middle.zymk"},{"clipname":"裁剪比例1：1","clipsize":[400,400],"osspath":"test3.jpg","previewHost":"","suffix":"-middle.zymk"},{"clipname":"裁剪比例4：3","clipsize":[800,600],"osspath":"test4","previewHost":"","suffix":"-middle.zymk"}]'></span>
                        <span class="glyphicon glyphicon-minus-sign face-icon face-icon-bottom e-clear"></span>
                    </div>
                    <input type="hidden" name="img_clip" class="e-host">
                </div>
            </div>
            <div class="col-md-3 handle-block">
                <div class="blank12"></div>
                <div class="form-group form-group-sm w150 margin-auto">
                    <input type="number" class="form-control" placeholder="" value="1">
                </div>
            </div>
            <div class="col-md-2 handle-block">
                <span class="handle-delete e-delete">删除</span>
            </div>
        </form>
    </div>
</script>
<!--a:裁剪modal end-->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/cropper.js"></script>
<!--签名相关start-->
<script type="text/javascript" src="lib/crypto/crypto/crypto.js"></script>
<script type="text/javascript" src="lib/crypto/hmac/hmac.js"></script>
<script type="text/javascript" src="lib/crypto/sha1/sha1.js"></script>
<script type="text/javascript" src="lib/base64.js"></script>
<!--cropper裁剪功能封装-->
<script src="js/comic_cropper.js"></script>
<script>

    var DEF_IMG="img/blank.jpg";//默认未裁剪封面图片
    var DEF_VIEW="img/blank.jpg";//默认样式图
    var IMG_SAVE_HOST = 'http://colputest.oss-cn-shanghai.aliyuncs.com';//上传图片路径
    var FIRE_NAME="";//上传图片文件名
    var DIR_NAME="";//上传图片文件目录

    var UPLOAD_SIZE=[//图片上传大小转换
        [160,80],  //16：8  即160x80
        [400,300], //4：3 即400x300
        [150,200]  //3：4 即150x200
    ];

//    变动：
    var CLIP_CONFIG={
        accessid: 'LTAIIBhmANgKIrMQ',
        accesskey: 'm9NnFlYFYR4fkXidX8gjtTsnssy9mf',
        host: 'http://colputest.oss-cn-shanghai.aliyuncs.com'//上传图片路径
    };
    $(function(){
        var handleContainer = $("#handle");
        var publicfields = $("#publicfields");
        var addBookBtn=$("#addBookBtn");
//裁剪功能逻辑

        var clipImg = {
            cropper: null,
            modal: $("#clipModal"),
            inputImage: "inputImage",
            uploadHost: null,
            filename: null,
            dirname: null,
            saveCall: null,
            cacheData:[],
            init: function (host, filename, dirname) {
                if (!host) {
                    console.error("缺少图片上传路径!");
                }
                this.uploadHost = host;
                this.filename = filename;
                this.dirname = dirname;
                var self=this;
                //设置裁剪回调
                var option={
                    actions: '#actions',
                    container: '.img-container',
                    inputImage: this.inputImage,
                    aspectRatio:parseFloat($('input[name=aspectRatio]').eq(0).val()),
                    dragMode:"move",
                    cropBoxMovable:false,
                    cropBoxResizable:false,
                    cropperDataType: false,
                    minCropBoxWidth:99999,//插件内部做了边界判断，设为较大值是为了让裁剪框最大边抵拢边框
                    getCropperData: function (data) {
                        if(data){
//                            clipImg.send(data);
                            var index=$('div[data-toggle="buttons"]').children(".active").index();
                            self.cacheData[index]=data;
                            //先保存到右边预览框
                            readBlobAsDataURL(data,function(dataUrl){
                                $(".toggle-view").eq(index).attr("src",dataUrl);
                            });
                        }
                    }
                };

                this.modal.modal({
                    show: false,
                    backdrop: 'static'
                }).on('shown.bs.modal', function () {
//                    $('#aspectRatio1').click();
                    //在第一次打开modal时初始化cropper 否则无法获取宽高而使插件初始化成默认宽高
                    if(!self.cropper){
                        self.cropper = new ComicCropper();
                        self.cropper.init(option);
                    }
                }).on('hidden.bs.modal', function () {
                    this.saveCall = null;
                    //隐藏modal时隐藏和重置所有预览和裁剪
//                    self.cropper.cropper.reset();
//                    $(".toggle-view").attr("src",DEF_IMG);
//                    self.cacheData=[];
                });
                //点击预览框选择当前尺寸图片上传,并且将此图片还原到裁剪框中
                var tw=$(".toggle-wrap");
                tw.children().on("click",function () {
                    var _t=$(this);
                    if(_t.hasClass("active")){
                        return false;
                    }
                    tw.find(".active").removeClass("active");
                    _t.addClass("active");
                    var _img=_t.find(".toggle-view");
                    var index=_t.parent().index();
                    if(self.cacheData[index]){
                        //重新初始化裁剪框
                        self.cropper.reloadImg(self.cacheData[index]);
                    }
                });
                //点击上传图片
                $(".clip-sub").on("click",function(){
                    var view=tw.find(".active");
                    var index=view.parents().index();
                    if(!self.cacheData[index]){
                        alert("尚未保存该尺寸的裁剪图片，请在左边进行图片裁剪操作再进行上传！");
                        return false;
                    }
                    var size=view.siblings(".toggle-size").text().replace(/(^\s*)|(\s*$)/g,"");
                    if(confirm("确定要保存尺寸为:"+size+" 的图片吗？")){
                        self.send(index);
                    }
                })
            },
            showModal: function (callBack) {
                this.modal.modal("show");
                this.saveCall = callBack || null;
            },
            send: function (p) {
                var _this = this;
                var cropperData=p;
                var scale=null;
                var sourceImg=null;
                if(typeof cropperData === "number"){
                    scale=UPLOAD_SIZE[cropperData];
                    sourceImg=$(".toggle-view").eq(cropperData)[0];
                    cropperData=this.cacheData[cropperData];
                    //需要对图片进行缩放
                    var cv=document.createElement("canvas");
                    cv.width=scale[0];
                    cv.height=scale[1];
                    cv.getContext('2d').drawImage(sourceImg, 0, 0, scale[0], scale[1]);
                    cover(1);
                    cropperData=cv.toBlob(function(b){
                        cover(0);
                        doSend(b);
                    });
                    return false;
                }
                else {
                    doSend(cropperData)
                }
                if(!cropperData){
                    throw Error("获取不到clipdata！");
                }
                function doSend(b){
                    // 获得裁剪后的数据上传
                    var options = getUploadConfig({
                        accessid: 'LTAIIBhmANgKIrMQ',
                        accesskey: 'm9NnFlYFYR4fkXidX8gjtTsnssy9mf',
                        filename: _this.filename || _this.cropper.uploadedImageName,  // 上传文件名称可以在这里自己指定，默认为上传图片名称
                        dirname: _this.dirname || '' // 上传目录
                    });
                    $.ajax({
                        url: _this.uploadHost,
                        type: 'post',
                        contentType: false,
                        processData: false,
                        async: true, // 发送同步请求
                        cache: false, // 设置为false将不会从浏览器缓存中加载请求信息
                        data: installFormData(options, b),
                        success: function (res, req) {
                            var src = _this.uploadHost + '/' + options.dirname + options.filename;
                            alert('上传图片成功: ' + src);
                            _this.saveCall && _this.saveCall(src) && (_this.saveCall = null);
                            _this.modal.modal("hide");
                        },
                        error: function (res) {
                            cover(0);
                            alert('上传图片出错', res);
                        }
                    });
                }
            }
        };

        /*init*/
        clipImg.init(CLIP_CONFIG);
//        clipImg.init(IMG_SAVE_HOST, DIR_NAME, FIRE_NAME);
//event
//列表事件统一管理部分
        handleContainer.on("click", ".e-add", function (e) {
            //裁剪上传图片
            var p = $(this).parents(".e-face");
            var pic = p.find(".e-pic");
            var picHost = p.find(".e-host");
            var configData=p.data('config');
            clipImg.showModal(function (src) {
                pic.attr("src", src);
                picHost.val(src);
            });
        }).on("click", ".e-clear", function (e) {
            //清除当前图片路径
            if (confirm("是否清空该图片？")) {
                var p = $(this).parents(".e-face");
                var pic = p.find(".e-pic");
                var picHost = p.find(".e-host");
                pic.attr("src", DEF_IMG);
                picHost.val("");
            }
        }).on("click",".e-delete",function(){
            var row=$(this).parents(".e-body").remove();
        });
        //添加新行
        addBookBtn.on("click",function(e){
            var index=handleContainer.find(".e-body").length;
            handleContainer.append(simpleTpl("bookTpl",{index:index++}));
        });
//遮罩层显示、隐藏
        function cover(show) {
            !cover["_layer"] && (cover["_layer"] = $("#cover"));
            cover["_layer"][!!show ? "show" : "hide"]();
        }
//获取当前form中的所有数据、设置当前form中的所有控件数据为对象属性
        function handleFormData($dom, obj) {
            if (!handleFormData._public) {
                handleFormData._public = {};
                publicfields.find("input,select,textarea").each(function (index) {
                    var _t = $(this);
                    var _n = _t.attr("name");
                    var _v = _t.val();
                    _n !== undefined && (handleFormData._public[_n] = _v);
                });
            }
            !cover["_layer"] && (cover["_layer"] = $("#cover"));
            var form = $dom.parents("form").eq(0);
            if (!!obj) {
                if (typeof obj === "object") {
                    form.find("input,select,textarea").each(function (index) {
                        var _t = $(this);
                        var pp = obj[_t.attr("name")];
                        if (pp !== undefined) {
                            _t.attr("value", pp);
                        }
                    });
                }
            }
            else {
                var o = {};
                var fd = form.serializeArray().forEach(function (t) {
                    o[t.name] = t.value;
                });
                $.extend(true, o, handleFormData._public);
                return o;
            }
        }
// 很简易的模版处理(仅能处理对象的一级属性值，不能在模版中使用循环)
        //如果模版比较复杂 建议试用其他模版插件渲染
        function simpleTpl(tplId, data) {
            var tplStr = $("#" + tplId).html();
            var fn = function (str, obj) {
                return str.replace(/\<script/g, "&lt;script").replace(/\{\{([^\^\$]*?)\}\}/g, function (a, $1) {
                    return obj[$1] || "";
                }).replace(/\{\{\#\}\}/g, function (a, $1) {
                    return obj.toString();
                }).replace(/\{\{\^(.*?)\}\}([\s\S]*?)\{\{\$(.*?)\}\}/g,function(a,$1,$2,$3){
                    return ($1===$3&&!!obj[$1])?$2:""
                });
            };
            var strings="";
            if($.isArray(data)){
                for(var i=0;i<data.length;i++){
                    strings+=fn(tplStr,data[i]);
                }
            }
            else {
                strings=fn(tplStr,data);
            }
            return strings;
        }
// 配置图片上传
        function getUploadConfig(opt) {
            var policyText = {
                expiration: new Date(Date.now() + (opt.uploadExpire|| 36e5)), // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                conditions: [
                    ['content-length-range', 0, (opt.uploadMaxSize || 1048576000)] // 设置上传文件的大小限制
                ]
            };

            var message = Base64.encode(JSON.stringify(policyText));
            var bytes = Crypto.HMAC(Crypto.SHA1, message, opt.accesskey, {asBytes: true});
            var signature = Crypto.util.bytesToBase64(bytes);

            // 设置上传图片名字
            var filename = opt.filename || 'default.jpg';
            // 上传更目录不填写，存在目录以: **/**/方式构建目录
            var dirname = (function(dirname, filename) {
                if (!dirname) return '';
                return (dirname.lastIndexOf('/') >= 0 ? dirname : dirname + '/')
            })(opt.dirname, filename);

            return {
                Filename: '${filename}',
                key: dirname + '${filename}',
                policy: message,
                success_action_status: opt.success_action_status || '200', // 让服务端返回200,不然，默认会返回204
                OSSAccessKeyId: opt.accessid,
                signature: signature,
                filename: filename,
                dirname: dirname
            }
        }
// 组装上传图片FormData
        function installFormData(options, data) {
            var formData = new FormData();
            // 将配置追加到formData数据中
            $.each({
                Filename: options.Filename,
                key: options.key,
                policy: options.policy,
                success_action_status: options.success_action_status,
                OSSAccessKeyId: options.OSSAccessKeyId,
                signature: options.signature
            }, function(key, item) {
                formData.append(key, item)
            });
            // 获取到formData数据，可提POST提交套服务器
            formData.set('file', data, options.filename);
            return formData;
        }
    });
    //转化blob对象为dataurl
    function readBlobAsDataURL(blob, callback) {
        var a = new FileReader();
        a.onload = function(e) {callback(e.target.result);};
        a.readAsDataURL(blob);
    }
</script>
</body>
</html>